/*
* @Date: 2021/2/23
* @Author: XueChengwu <xuechengwu@erayt.com>
* @Copyright: 2015-2019 Erayt, Inc.
* @Description: If you have some questions, please contact: xuechengwu@erayt.com.
*/
import controller from '../core/controller'
import { get, post } from '../core/route';
import { db, tran, id } from '../core/db/mysql/db';
import Query from '../core/db/mysql/query';
import { check_captcha, no_repeat } from '../behaviour/common';
import { login } from '../decorater/auth';
import Validator from '../core/validator'
import UserValidator from '../validator/buUser';
import i18n from '../core/i18n';
import utils from '../core/utils';
import md5 from 'md5';

@controller()
export default class user{
  @post('/front/register')
  async register() {
    const user = this.params;
    let validator = new Validator(UserValidator);
    let res = await validator.scene('register').check(user);
    if(res !== true) {
      return this.setCode(1).setMsg(res).json();
    }
    const tranResult = await tran(async conn => {
      if(!await this.__todo(no_repeat, conn, this.params, 'username', 'bu_user')){
        return this.setMsg(i18n.repeat.username), false
      }
      try {
        const userQuery = new Query(conn, 'bu_user');
        const userModal = {
          addtime: utils.formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss'),
          password: md5(user.password),
          username: user.username,
          tel: user.tel || '',
          email: user.email,
        };
        await userQuery.insert(userModal);
        return true;
      } catch(err) {
        throw err;
        return false;
      }
    });
    if (tranResult) {
      return this.setCode(0).json();
    }
    return this.setCode(1).json();
  }

  @get('/front/register')
  async getRegister() {
    const page = await this.fetch('front/register');
    return page;
  }

  @get('/front/login')
  async getLogin() {
    let page = await this.fetch('front/logon');
    return page;
  }

  @post('/front/login')
  async login() {
    let validator = new Validator(UserValidator);
    let res = await validator.scene('login').check(this.params)
    if(res !== true) {
      return this.setCode(1).setMsg(res).json()
    }
    const passResult = await db(async conn => {
      try{
        let query = new Query(conn, 'bu_user')
        const username = this.params.username;
        let res = await query.where('username', username).where('or', 'tel', username).find();
        if(res && res.password === md5(this.params.password)){
          this.session.userid = res.id;
          this.session.username = res.username;
          delete res.password;
          this.assign('user', res);
          return true
        }else {
          return false
        }
      }catch(err) {
        return false
      }
    });
    if (passResult) {
      return this.setCode(0).setMsg(i18n.user.login.success).json();
    }
    return this.setCode(1).setMsg(i18n.user.login.error).json();
  }

  @login
  @post('/api/logout')
  async logout() {

  }
  @login
  @get('front/center')
  async center() {
    const page = await this.fetch('front/center');
    return page;
  }

  @login
  @get('front/getProjects')
  async getProjects() {
    const { userid } = this.session;
    let result = await db(async conn => {
      try {
        let projectQuery = new Query(conn, 'bu_project');
        const projects = await projectQuery.where('author', userid).select();
        this.assign('projects', projects);
        return true;
      } catch(err) {
        console.log('err====>', err);
        return false;
      }
    });
    if (result) {
      return this.setCode(0).setMsg('获取成功').json();
    }
    return this.setCode(1).setMsg('获取失败').json();
  }

  @login
  @post('front/addProject')
  async addProject() {
    const { userid } = this.session;
    const { name, description } = this.params;
    if (name === undefined || name === '') {
      return this.setCode(1).setMsg('应用名称不能为空').json();
    }
    let result = await db(async conn => {
      try {
        const projectQuery = new Query(conn, 'bu_project');
        const shortcode = utils.getGuid();
        const projectModel = {
          name,
          description,
          author: userid,
          addtime: utils.formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss'),
          level: 1,
          shortcode,
          ispub: 0,
        };
        const res = await projectQuery.insert(projectModel);
        this.assign('shortcode', shortcode);
        return true;
      } catch(err) {
        console.log('err====>', err);
        return false;
      }
    });
    if (result) {
      return this.setCode(0).setMsg('新增成功').json();
    }
    return this.setCode(1).setMsg('新增失败').json();
  }
}
